package cn.yoyo.dao;

import com.mongodb.client.gridfs.model.GridFSFile;
import org.bson.types.ObjectId;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.gridfs.GridFsResource;
import org.springframework.data.mongodb.gridfs.GridFsTemplate;
import org.springframework.stereotype.Repository;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;

@Repository
public class LargefileDaoImpl implements LargefileDao {
    @Autowired
    GridFsTemplate gridFsTemplate;
    @Override
    public String saveMultipartFile(MultipartFile file) throws Exception{
        String fileName = file.getOriginalFilename();
        // 获得文件输入流
        InputStream ins = file.getInputStream();
        // 获得文件类型
        String contentType = file.getContentType();
        // 将文件存储到mongodb中,mongodb 将会返回这个文件的具体信息
        //gridFsTemplate.store();
        ObjectId objectId = gridFsTemplate.store(ins,fileName,contentType);
        //将文件信息保存到关系型数据库中进行维护
        return objectId.toHexString();
    }

    @Override
    public InputStream getInpuStreamById(String id) throws IOException {
        System.out.println("Getting file.. id=" + id);
        GridFSFile result = gridFsTemplate
                .findOne(new Query(Criteria.where("_id").is(id)));
        if (result == null) {
            return null;
        }
        GridFsResource resource = gridFsTemplate.getResource(result);
        return resource.getInputStream();
    }

    @Override
    public void deleteById(String imgId) {
        gridFsTemplate.delete(new Query(Criteria.where("ID").is(imgId)));
    }
}
